package com.wangbo.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CGLibProxy<T> implements MethodInterceptor {

    public T createProxy(Class<? extends T> clazz) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return (T) enhancer.create(); // 返回代理对象
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        Object result = methodProxy.invokeSuper(obj, args);
        // 添加用户时模拟增强
        if ("addUser".equals(method.getName())) {
            mockEnhance();
        }
        return result;
    }

    /**
     * 模拟增强
     */
    private void mockEnhance() {
        System.out.println("~~~模拟增强~~~");
    }
}
